package practise2.oneHundredQuestion;

import practise2.model.BidirectionLinkedNode;
import practise2.model.LinkedNode;
import practise2.model.TreeNode;
import practise2.util.CreateTree;

import java.util.Arrays;

/**
 * Created by Richard on 1/8/2015.
 */
public class ConvertTreeToBirdectionLink {
    public static BidirectionLinkedNode<Integer> convert(TreeNode<Integer> head){
        BidirectionLinkedNode<Integer> linkedNodeHead = new BidirectionLinkedNode<>();
         convertRecursive(head,linkedNodeHead);
        return linkedNodeHead;
    }

    private static BidirectionLinkedNode<Integer> convertRecursive(TreeNode<Integer> node, BidirectionLinkedNode<Integer> bidirectionLinkedNode){
        if(node==null){
            return bidirectionLinkedNode;
        }
        if(node.getLeftNode()==null && node.getLeftNode()==null){
            bidirectionLinkedNode.setValue(node.getValue());
            bidirectionLinkedNode.setNext(new BidirectionLinkedNode<>());
            bidirectionLinkedNode.getNext().setPrevious(bidirectionLinkedNode);
            return bidirectionLinkedNode.getNext();
        }

        bidirectionLinkedNode =  convertRecursive(node.getLeftNode(), bidirectionLinkedNode);

        bidirectionLinkedNode.setValue(node.getValue());
        bidirectionLinkedNode.setNext(new BidirectionLinkedNode<>());
        bidirectionLinkedNode.getNext().setPrevious(bidirectionLinkedNode);
        bidirectionLinkedNode = bidirectionLinkedNode.getNext();

        return convertRecursive(node.getRightNode(), bidirectionLinkedNode);

    }

    public static void main(String[] args){
        TreeNode<Integer> treeNode = CreateTree.createATreeFromArray(Arrays.asList(new Integer[]{1,2,3,4,5,6,7,8}));
        BidirectionLinkedNode<Integer> node = convert(treeNode);
        node.getPrevious();
    }
}
